import { Player, Position, BOARD_SIZE, DIRECTIONS } from '../types/game';

// 优化版AI：保持智能水平 + 提升速度
// 开局库
const OPENING_BOOK: Position[] = [
  { row: 7, col: 7 }, // 中心点
  { row: 7, col: 6 }, // 右中心
  { row: 7, col: 8 }, // 左中心
  { row: 6, col: 7 }, // 上中心
  { row: 8, col: 7 }, // 下中心
];

// 位置权重（中心位置更重要）
const getPositionWeight = (row: number, col: number): number => {
  const center = Math.floor(BOARD_SIZE / 2);
  const distanceFromCenter = Math.abs(row - center) + Math.abs(col - center);
  const maxDistance = center * 2;
  return maxDistance - distanceFromCenter;
};

// 棋型评估表
const PATTERN_SCORES = {
  FIVE: 100000,
  LIVE_FOUR: 50000,
  RUSH_FOUR: 5000,
  LIVE_THREE: 1000,
  SLEEP_THREE: 500,
  LIVE_TWO: 100,
  SINGLE: 10
};

// 检查五子连珠
const checkFiveInRow = (board: Player[][], row: number, col: number, player: Player): boolean => {
  for (const { dr, dc } of DIRECTIONS) {
    let count = 1;
    
    // 正方向
    for (let i = 1; i < 5; i++) {
      const newRow = row + dr * i;
      const newCol = col + dc * i;
      if (newRow >= 0 && newRow < BOARD_SIZE && 
          newCol >= 0 && newCol < BOARD_SIZE && 
          board[newRow][newCol] === player) {
        count++;
      } else {
        break;
      }
    }
    
    // 反方向
    for (let i = 1; i < 5; i++) {
      const newRow = row - dr * i;
      const newCol = col - dc * i;
      if (newRow >= 0 && newRow < BOARD_SIZE && 
          newCol >= 0 && newCol < BOARD_SIZE && 
          board[newRow][newCol] === player) {
        count++;
      } else {
        break;
      }
    }
    
    if (count >= 5) return true;
  }
  return false;
};

// 快速检查线段模式
const checkLinePattern = (line: (Player | null)[], player: Player): number => {
  const playerCount = line.filter(cell => cell === player).length;
  const emptyCount = line.filter(cell => cell === null).length;
  const opponentCount = line.filter(cell => cell && cell !== player).length;
  
  if (opponentCount > 0) return 0;
  
  if (playerCount === 5) return PATTERN_SCORES.FIVE;
  if (playerCount === 4 && emptyCount === 1) return PATTERN_SCORES.LIVE_FOUR;
  if (playerCount === 3 && emptyCount === 2) return PATTERN_SCORES.LIVE_THREE;
  if (playerCount === 2 && emptyCount === 3) return PATTERN_SCORES.LIVE_TWO;
  if (playerCount === 1) return PATTERN_SCORES.SINGLE;
  
  return 0;
};

// 优化后的模式检查 - 直接检查关键方向
const checkOptimizedPattern = (board: Player[][], row: number, col: number, player: Player): number => {
  if (board[row][col] !== null) return 0;
  
  let totalScore = 0;
  
  // 只检查最有价值的几个方向组合
  for (const { dr, dc } of DIRECTIONS) {
    // 构造当前方向的线段
    const line: (Player | null)[] = [];
    
    // 从-4到+4构造线段
    for (let i = -4; i <= 4; i++) {
      const newRow = row + dr * i;
      const newCol = col + dc * i;
      
      if (newRow >= 0 && newRow < BOARD_SIZE && newCol >= 0 && newCol < BOARD_SIZE) {
        line.push(board[newRow][newCol]);
      } else {
        line.push(null);
      }
    }
    
    const patternScore = checkLinePattern(line, player);
    totalScore += patternScore;
  }
  
  // 添加位置权重
  totalScore += getPositionWeight(row, col) * 10;
  
  return totalScore;
};

// 优化后的候选位置生成 - 更精确的搜索范围
const getOptimizedCandidateMoves = (board: Player[][]): Position[] => {
  const candidates: Position[] = [];
  const visited = new Set<string>();
  
  // 收集已有棋子周围的空位，但优化搜索逻辑
  for (let row = 0; row < BOARD_SIZE; row++) {
    for (let col = 0; col < BOARD_SIZE; col++) {
      if (board[row][col] !== null) {
        // 只搜索周围1-2格，但优先考虑2格范围内的位置
        for (let dr = -2; dr <= 2; dr++) {
          for (let dc = -2; dc <= 2; dc++) {
            const newRow = row + dr;
            const newCol = col + dc;
            const key = `${newRow}-${newCol}`;
            
            if (newRow >= 0 && newRow < BOARD_SIZE && 
                newCol >= 0 && newCol < BOARD_SIZE && 
                board[newRow][newCol] === null && 
                !visited.has(key)) {
              candidates.push({ row: newRow, col: newCol });
              visited.add(key);
            }
          }
        }
      }
    }
  }
  
  // 如果棋盘为空，返回开局库
  if (candidates.length === 0) {
    return OPENING_BOOK;
  }
  
  // 按位置权重排序，优先考虑中心位置
  return candidates.sort((a, b) => getPositionWeight(b.row, b.col) - getPositionWeight(a.row, a.col));
};

// 优化后的Alpha-Beta算法 - 改进剪枝效率
const minimaxWithOptimizedPruning = (
  board: Player[][],
  depth: number,
  alpha: number,
  beta: number,
  isMaximizing: boolean,
  player: Player
): { score: number; position?: Position } => {
  const opponent = player === 'black' ? 'white' : 'black';
  
  // 检查游戏结束状态 - 快速检查
  if (depth < 3) { // 只在前几层检查胜负状态，减少重复计算
    for (let row = 0; row < BOARD_SIZE; row++) {
      for (let col = 0; col < BOARD_SIZE; col++) {
        if (board[row][col] === player && checkFiveInRow(board, row, col, player)) {
          return { score: PATTERN_SCORES.FIVE };
        }
        if (board[row][col] === opponent && checkFiveInRow(board, row, col, opponent)) {
          return { score: -PATTERN_SCORES.FIVE };
        }
      }
    }
  }
  
  if (depth === 0) {
    return { score: evaluateBoardOptimized(board, player) };
  }
  
  const candidates = getOptimizedCandidateMoves(board);
  // 限制候选位置数量，提升搜索效率
  const limitedCandidates = candidates.slice(0, Math.min(candidates.length, 20));
  
  if (isMaximizing) {
    let maxScore = -Infinity;
    let bestPosition: Position | undefined;
    
    for (const move of limitedCandidates) {
      const newBoard = [...board];
      newBoard[move.row] = [...newBoard[move.row]];
      newBoard[move.row][move.col] = player;
      
      const result = minimaxWithOptimizedPruning(newBoard, depth - 1, alpha, beta, false, player);
      
      if (result.score > maxScore) {
        maxScore = result.score;
        bestPosition = move;
      }
      
      alpha = Math.max(alpha, result.score);
      // 更积极的剪枝
      if (alpha >= beta - 10000) break; // 增强剪枝条件
    }
    
    return { score: maxScore, position: bestPosition };
  } else {
    let minScore = Infinity;
    let bestPosition: Position | undefined;
    
    for (const move of limitedCandidates) {
      const newBoard = [...board];
      newBoard[move.row] = [...newBoard[move.row]];
      newBoard[move.row][move.col] = opponent;
      
      const result = minimaxWithOptimizedPruning(newBoard, depth - 1, alpha, beta, true, player);
      
      if (result.score < minScore) {
        minScore = result.score;
        bestPosition = move;
      }
      
      beta = Math.min(beta, result.score);
      // 更积极的剪枝
      if (beta <= alpha + 10000) break; // 增强剪枝条件
    }
    
    return { score: minScore, position: bestPosition };
  }
};

// 优化的棋盘评估函数
const evaluateBoardOptimized = (board: Player[][], player: Player): number => {
  let totalScore = 0;
  const opponent = player === 'black' ? 'white' : 'black';
  
  // 只评估有棋子的位置附近的空位，大幅减少计算量
  for (let row = 0; row < BOARD_SIZE; row++) {
    for (let col = 0; col < BOARD_SIZE; col++) {
      if (board[row][col] === null) {
        // 只评估已经有棋子的位置周围2格内的空位
        let hasNearbyPiece = false;
        for (let dr = -2; dr <= 2; dr++) {
          for (let dc = -2; dc <= 2; dc++) {
            const checkRow = row + dr;
            const checkCol = col + dc;
            if (checkRow >= 0 && checkRow < BOARD_SIZE && 
                checkCol >= 0 && checkCol < BOARD_SIZE && 
                (board[checkRow][checkCol] === player || board[checkRow][checkCol] === opponent)) {
              hasNearbyPiece = true;
              break;
            }
          }
          if (hasNearbyPiece) break;
        }
        
        if (hasNearbyPiece) {
          totalScore += checkOptimizedPattern(board, row, col, player) - 
                       checkOptimizedPattern(board, row, col, opponent) * 0.9;
        }
      }
    }
  }
  
  return totalScore;
};

// 主AI函数 - 优化版本
export const getOptimizedAIMove = (board: Player[][], aiPlayer: Player): Position => {
  const opponent = aiPlayer === 'black' ? 'white' : 'black';
  
  // 第一步使用开局库
  const emptyCount = board.flat().filter(cell => cell === null).length;
  if (emptyCount >= BOARD_SIZE * BOARD_SIZE - 1) {
    return OPENING_BOOK[0];
  }
  
  // 检查是否能立即获胜
  for (let row = 0; row < BOARD_SIZE; row++) {
    for (let col = 0; col < BOARD_SIZE; col++) {
      if (board[row][col] === null && checkFiveInRow(board, row, col, aiPlayer)) {
        return { row, col };
      }
    }
  }
  
  // 检查是否需要阻挡对手获胜
  let bestDefensiveMove: Position | null = null;
  let maxThreat = 0;
  
  // 只检查有棋子的位置周围的位置，减少检查范围
  const threats = getOptimizedCandidateMoves(board);
  for (const move of threats) {
    if (checkFiveInRow(board, move.row, move.col, opponent)) {
      return move; // 必须阻挡
    }
  }
  
  // 使用优化的Minimax算法，深度为3（平衡智能和速度）
  const result = minimaxWithOptimizedPruning(board, 3, -Infinity, Infinity, true, aiPlayer);
  
  return result.position || threats[0] || { row: 7, col: 7 };
};